import { InjectionKey } from "vue";
import { createStore, useStore as baseUseStore, Store } from "vuex";
import user, { UserState } from "./modules/user";
import menu, { MenuState } from "./modules/menu";
import { useI18n } from "/@/locales/useI18n";

export interface RootState {
  //全局loading状态
  globalLoading: boolean;
  globalLoadingText: string;
  pageLoading: boolean;
}

interface AllState extends RootState {
  user: UserState;
  menu: MenuState;
  tenant: any;
}

export const key: InjectionKey<Store<RootState>> = Symbol();

export const store = createStore<RootState>({
  state: {
    globalLoading: false,
    globalLoadingText: "",
    pageLoading: false,
  },
  mutations: {
    setLoading(state, payload) {
      state.globalLoading = payload.loading;
      if (!payload.text) {
        const { t } = useI18n();
        payload.text = t("common.loading");
      }
      state.globalLoadingText = payload.text;
    },
    setPageLoading(state, payload) {
      state.pageLoading = payload.loading;
    },
  },
  actions: {
    toggleLoading({ commit }, payload) {
      commit("setLoading", payload);
    },
    togglePageLoading({ commit }, payload) {
      commit("setPageLoading", payload);
    },
  },
  modules: {
    user,
    menu,
  },
});

export function useStore<T = AllState>() {
  return baseUseStore<T>(key);
}
